window.AppContext = ( function() {
	
	function fetchAndParse( URL ) {
		return fetch( URL ).then( ( response ) => {
			return response.text();
		} ).then( ( html ) => {
			const parser = new DOMParser();
			const document = parser.parseFromString( html, 'text/html' );
			const head = document.head;
			const template = head.querySelector( 'template' );
			const style = head.querySelector( 'style' );
			const script = head.querySelector( 'script' );

			
			//console.log(style);
			
			return {
				template,
				style,
				script
			};
		} );
	}
	

	
	function getSettings( { template, style, script } ) {
		const jsFile = new Blob( [ script.textContent ], { type: 'application/javascript' } );
		const jsURL = URL.createObjectURL( jsFile );
		return import( jsURL ).then( ( module ) => {
			/*
			  //渲染元素
			  return {
				module:module.default,
				template,
				style
			  }
			*/
			
			//console.log(template);
            registerComponent({module: module.default, template, style });
			
            /*
            var fragment = document.createDocumentFragment();
            var tag = document.createElement("haha-haha");
            tag.style.display="none";
            tag.id="tag1"
            fragment.appendChild(tag);
            document.body.appendChild(fragment);
           */
           
            
			//module.default.template=template;
            //module.default.template=template.content;
			module.default.template="<haha-haha></haha-haha>";
			//module.default.mounted=function() {
			//	 registerComponent1({ template, style });
			//}
			
			//module.default.template="<div is='expanding-div'></div>";
			//module.default.template= document.querySelector('#tag1').shadowRoot.querySelector("#rootDiv");
			//module.default.el= document.querySelector('#tag1').shadowRoot.querySelector("#rootDiv");
			
			//var docFragment = document.createDocumentFragment();
			//var node = document.createElement('haha-haha');
			//docFragment.appendChild(node);
			//console.log( docFragment.innerHTML);
			
			    //var root = document.body.createShadowRoot();
			    //var clone = document.importNode(template.content, true);
			    //root.appendChild(clone);
			    
			    //console.log(root.innerHTML);
			    
			    
			    

			
			
			/*module.default.render= function (createElement) {
				
				 var e = createElement('haha-haha');
				 console.log(e);
				 return e;
		         //return createElement(module.default.name);
				 //return createElement('haha-haha')
			}*/
			
			return  module.default;
			/*const shadowRoot = document.querySelector('#tag1').shadowRoot;
			return new Vue(  {
					    el: shadowRoot.querySelector('#app'),
					    methods:{
							  testClick() {
								  alert('demo-comp click');
							  }
							}
			      });*/
			
			
			
		} );
	}
	

	function loadComponentAsyn (url,context) {
		 return function(){
				     return  {
				        component:  fetchAndParse( url+"?t="+(new Date().getTime())).then(getSettings)// 不渲染元素
				        	      /*
				        	       new Promise (function (resolve, reject){
				        	              //渲染元素但是没有响应方法
				        	              fetchAndParse( url+"?t="+(new Date().getTime()))
				        	             .then(getSettings)
				        	             .then(registerComponent)
				        	             .then((module)=>{
				        	            	 var  defautOptions={
				        	            			 methods:{
				        	            				  testClick() {
				        	            					  hello('demo-comp click');
				        	            				  }
				        	            			 }
				        	            	 };
					                         defautOptions.template="<demo-comp></demo-comp>";
					                         resolve (defautOptions);
				        	             });
                                   })
                                   */
				        ,
				        /* 加载过程中显示的组件 */
				        loading: {
				            template: '<p>加载中...</p>'
				        },
				        /* 出现错误时显示的组件  */
				        error: {
				            template: '<p style="color:red;">load failed!</p>'
				        },
				        /* loading组件的延迟时间 */
				        delay: 10,
				        /* 最长等待时间，如果超过此时间，将显示error组件。 */
				        timeout:3200
				    };
		}
    }
	
	
	function loadComponent (url,options){
  	  return loadComponentAsyn(url,options);
  	}
	
	function createComponent (tagName,templateUrl,dialogOptions){
    	 return Vue.component(tagName,()=>loadComponent(templateUrl,dialogOptions));
    }
	
	
	function registerComponent1( { template, style } ) {
		class ExpandingDiv extends  HTMLDivElement {
			
			constructor() {
			    // 必须首先调用 super方法 
			    super();
			    this._upcast();
			    
			    
			    
			}
			
			/*connectedCallback() {
				this._upcast();
			}*/

			_upcast() {
				const shadow = this.attachShadow( { mode: 'open' } );
				shadow.appendChild( style.cloneNode( true ) );
				shadow.appendChild( document.importNode( template.content, true ) );
			}
		}
		
		// Define the new element
		return customElements.define('expanding-div', ExpandingDiv, { extends: 'div' });
		
	}
	
	
	
	function registerComponent( {module, template, style } ) {
		class UnityComponent extends HTMLElement {
			connectedCallback() {
				this._upcast();
				//this._attachListeners();
				//var p = this.parentNode;
			    //console.log(p);
				
			
				var r=this.shadowRoot;
				new Vue({
				    el: r.querySelector('#rootDiv'),
				    data:{
				    	msg:'hello word'
				    },
				    methods:{
						  testClick() {
							  alert('demo-comp click');
						  }
						}
				})
				
			}

			_upcast() {
				const shadow = this.attachShadow( { mode: 'open' } );
				shadow.appendChild( style.cloneNode( true ) );
				shadow.appendChild( document.importNode( template.content, true ) );
			}

			//_attachListeners() {
			//	Object.entries( listeners ).forEach( ( [ event, listener ] ) => {
			//		this.addEventListener( event, listener, false );
			//	} );
			//}
		}

		 //https://developer.mozilla.org/zh-CN/docs/Web/API/CustomElementRegistry/define
		 //该函数返回值为空
		 //return customElements.define( module.name, UnityComponent );
		try{
		   //var a=  customElements.whenDefined("haha-haha");
		   //console.log(a);
		   return customElements.define("haha-haha", UnityComponent );
		}catch(e){
			
		}
		 //module.template="<demo-comp></demo-comp>";
          //return module;
		
		/*return new Promise (function (resolve, reject){
			                         var  defautOptions=module;
			                         defautOptions.template="<hello-world></hello-world>"
			                         resolve (defautOptions);
		                    });*/
		                   
	}
  /*
	function loadComponent( URL ) {
		return fetchAndParse( URL ).then( ({ template, style, script })=>{
			console.log(template);
			console.log(style);
			console.log(script);
		} );
		//.then( getSettings )
		//.then( registerComponent );
	}
    */
	
	return {loadComponentAsyn,loadComponent};
	
}() );
